import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Typography, Tag, message, Modal, Form, Input, Select, InputNumber, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, BookOutlined, UploadOutlined } from '@ant-design/icons';
import { fetchNovels as fetchNovelsApi, deleteNovel as deleteNovelApi, createNovel, updateNovel } from '../services/novelService';
import { queryNovelChapters, addNovelChapter, updateNovelChapter, deleteNovelChapter, readNovelChapter } from '../services/novelService';
import { Novel, NovelChapter } from '../types/novel';


const { Title } = Typography;

const NovelStore: React.FC = () => {
  // State for novels data
  // Pagination states
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  // Data states
  const [novels, setNovels] = useState<Novel[]>([]);
  const [selectedNovel, setSelectedNovel] = useState<Novel | null>(null);
  const [chapters, setChapters] = useState<NovelChapter[]>([]);
  // Loading states
  const [loading, setLoading] = useState(false);
  const [chapterLoading, setChapterLoading] = useState(false);
  // Modal states
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [chapterModalVisible, setChapterModalVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [filePath, setFilePath] = useState('');
  const [importLoading, setImportLoading] = useState(false);
  const [showChapters, setShowChapters] = useState(false);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [chapterModalType, setChapterModalType] = useState<'add' | 'edit'>('add');
  // Chapter pagination states
  const [chapterCurrentPage, setChapterCurrentPage] = useState(1);
  const [chapterPageSize, setChapterPageSize] = useState(10);
  const [chapterTotal, setChapterTotal] = useState(0);
  // Form instances
  const [form] = Form.useForm();
  const [chapterForm] = Form.useForm();

  // Fetch novels data from API
  // Fetch novels with pagination
  const fetchNovels = async (newPageNum?: number, newPageSize?: number) => {
    setLoading(true);
    try {
      const response = await fetchNovelsApi({
        pageNum: newPageNum !== undefined ? newPageNum : currentPage,
        pageSize: newPageSize !== undefined ? newPageSize : pageSize
      });
      setNovels(response.records);
      setTotal(response.total);
    } catch (error) {
      message.error('获取小说列表失败');
      console.error('Error fetching novels:', error);
    } finally {
      setLoading(false);
    }
  };

  // Handle table change for pagination
  const handleTableChange = (pagination: any) => {
    const newCurrentPage = pagination.current;
    const newPageSize = pagination.pageSize;
    setCurrentPage(newCurrentPage);
    setPageSize(newPageSize);
    fetchNovels(newCurrentPage, newPageSize);
  };

  // Show add novel modal
  const showAddModal = () => {
    setModalType('add');
    form.resetFields();
    setIsModalVisible(true);
  };

  // Show edit novel modal
  const showEditModal = (record: Novel) => {
    setModalType('edit');
    setSelectedNovel(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  // Handle novel form submission
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const novelData: Novel = {
        ...values,
        id: modalType === 'edit' && selectedNovel ? selectedNovel.id : undefined
      };

      if (modalType === 'add') {
        await createNovel(novelData);
        message.success('小说添加成功');
      } else {
        await updateNovel(novelData);
        message.success('小说更新成功');
      }

      setIsModalVisible(false);
      fetchNovels();
    } catch (error) {
      console.error('提交表单失败:', error);
      message.error('提交表单失败，请重试');
    }
  };

  // Show chapters for selected novel
  const handleShowChapters = (record: Novel) => {
    setSelectedNovel(record);
    setShowChapters(true);
    setChapterCurrentPage(1);
    fetchChapters(record.id);
  };

  // Fetch chapters with pagination
  const fetchChapters = async (novelId: string, pageNum?: number, pageSize?: number) => {
    setChapterLoading(true);
    try {
      // 使用传入的分页参数或当前状态值
      const currentPage = pageNum !== undefined ? pageNum : chapterCurrentPage;
      const currentPageSize = pageSize !== undefined ? pageSize : chapterPageSize;
      // 更新状态以确保UI显示正确的分页信息
      setChapterCurrentPage(currentPage);
      setChapterPageSize(currentPageSize);
      const response = await queryNovelChapters(
        novelId,
        currentPage,
        currentPageSize
      );
      setChapters(response.records);
      setChapterTotal(response.total);
    } catch (error) {
      message.error('获取章节列表失败');
      console.error('Error fetching chapters:', error);
    } finally {
      setChapterLoading(false);
    }
  };

  // Handle chapter table change
  const handleChapterTableChange = (pagination: any) => {
    setChapterCurrentPage(pagination.current);
    setChapterPageSize(pagination.pageSize);
    if (selectedNovel) {
      fetchChapters(selectedNovel.id, pagination.current, pagination.pageSize);
    }
  };

  // Show add chapter modal
  const showImportChapterModal = () => {
    setFilePath('');
    setImportModalVisible(true);
  };

  const handleImportChapter = async () => {
    if (!selectedNovel) return;
    if (!filePath.trim()) {
      message.error('请输入文件地址');
      return;
    }
    setImportLoading(true);
    try {
      await readNovelChapter(selectedNovel.id, filePath);
      message.success('章节导入成功');
      setImportModalVisible(false);
      fetchChapters(selectedNovel.id);
    } catch (error) {
      message.error('章节导入失败: ' + (error as Error).message);
    } finally {
      setImportLoading(false);
    }
  };

  const showAddChapterModal = () => {
    setChapterModalType('add');
    chapterForm.resetFields();
    setChapterModalVisible(true);
  };

  // Show edit chapter modal
  const showEditChapterModal = (record: NovelChapter) => {
    setChapterModalType('edit');
    chapterForm.setFieldsValue({ ...record, id: record.id });
    setChapterModalVisible(true);
  };

  // Handle chapter form submission
  const handleChapterSubmit = async () => {
    if (!selectedNovel) return;

    try {
      const values = await chapterForm.validateFields();
      const chapterData: NovelChapter = {
        ...values,
        novelId: selectedNovel.id,
        id: chapterModalType === 'edit' ? values.id : undefined
      };

      if (chapterModalType === 'add') {
        await addNovelChapter(chapterData);
        message.success('章节添加成功');
      } else {
        await updateNovelChapter(chapterData);
        message.success('章节更新成功');
      }

      setChapterModalVisible(false);
      fetchChapters(selectedNovel.id);
    } catch (error) {
      console.error('提交章节表单失败:', error);
      message.error('提交章节表单失败，请重试');
    }
  };

  // Handle chapter deletion
  const handleChapterDelete = async (id: string) => {
    if (!selectedNovel) return;

    try {
      await deleteNovelChapter(id);
      message.success('章节删除成功');
      fetchChapters(selectedNovel.id);
    } catch (error) {
      message.error('章节删除失败');
      console.error('Error deleting chapter:', error);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteNovelApi(id);
      message.success('小说删除成功');
      fetchNovels();
    } catch (error) {
      message.error('小说删除失败');
      console.error('Error deleting novel:', error);
    }
  };

  // Initial data fetch
  useEffect(() => {
    fetchNovels();
  }, []);

  // Chapter table columns configuration
  const chapterColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '章节标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" icon={<EditOutlined />} size="small" onClick={() => showEditChapterModal(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个章节吗?"
            onConfirm={() => handleChapterDelete(record.id)}
            okText="是"
            cancelText="否"
          >
            <Button danger icon={<DeleteOutlined />} size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // Table columns configuration
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        let color = 'orange';
        let label = '草稿';
        if (status === 'published') {
          color = 'green';
          label = '已发布';
        } else if (status === 'archived') {
          color = 'red';
          label = '已归档';
        }
        return <Tag color={color}>{label}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" icon={<EditOutlined />} size="small" onClick={() => showEditModal(record)}>
            编辑
          </Button>
          <Button type="default" icon={<BookOutlined />} size="small" onClick={() => handleShowChapters(record)}>
            章节管理
          </Button>
          <Popconfirm
            title="确定要删除这个小说吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="是"
            cancelText="否"
          >
            <Button danger icon={<DeleteOutlined />} size="small">
              删除
            </Button>
          </Popconfirm>

        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <Card title={showChapters ? `${selectedNovel?.title} - 章节管理` : "小说资源管理"} extra={showChapters ? (
          <Space>
            <Button onClick={() => setShowChapters(false)}>返回小说列表</Button>
            <Button type="primary" onClick={showAddChapterModal} icon={<PlusOutlined />}>
              添加章节
            </Button>
            <Button type="default" onClick={showImportChapterModal} icon={<UploadOutlined />}>
              导入章节
            </Button>
          </Space>
        ) : (
          <Button type="primary" icon={<PlusOutlined />} onClick={showAddModal}>添加新小说</Button>
        )}>
          {showChapters ? (
            <Table
              dataSource={chapters}
              columns={chapterColumns}
              rowKey="id"
              loading={chapterLoading}
              pagination={{
                current: chapterCurrentPage,
                pageSize: chapterPageSize,
                total: chapterTotal,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`,
                pageSizeOptions: ['10', '20', '50']
              }}
              onChange={handleChapterTableChange}
            />
          ) : (
            <Table
              dataSource={novels}
              columns={columns}
              rowKey="id"
              loading={loading}
              pagination={{
                current: currentPage,
                pageSize: pageSize,
                total: total,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`,
                pageSizeOptions: ['10', '20', '50']
              }}
              onChange={handleTableChange}
            />
          )}
          {/* Add/Edit Novel Modal */}
          <Modal
            title={modalType === 'add' ? "添加小说" : "编辑小说"}
            open={isModalVisible}
            onCancel={() => setIsModalVisible(false)}
            footer={[
              <Button key="cancel" onClick={() => setIsModalVisible(false)}>
                取消
              </Button>,
              <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
                {modalType === 'add' ? '添加' : '更新'}
              </Button>,
            ]}
          >
            <Form
              form={form}
              layout="vertical"
              name="novel_form"
            >
              <Form.Item
                name="title"
                label="小说标题"
                rules={[{ required: true, message: '请输入小说标题' }]}
              >
                <Input placeholder="请输入小说标题" />
              </Form.Item>

              <Form.Item
                name="author"
                label="作者"
                rules={[{ required: true, message: '请输入作者名称' }]}
              >
                <Input placeholder="请输入作者名称" />
              </Form.Item>

              <Form.Item
                name="category"
                label="分类"
                rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类">
                  <Select.Option value="玄幻">玄幻</Select.Option>
                  <Select.Option value="奇幻">奇幻</Select.Option>
                  <Select.Option value="科幻">科幻</Select.Option>
                  <Select.Option value="都市">都市</Select.Option>
                  <Select.Option value="言情">言情</Select.Option>
                  <Select.Option value="历史">历史</Select.Option>
                  <Select.Option value="军事">军事</Select.Option>
                  <Select.Option value="游戏">游戏</Select.Option>
                  <Select.Option value="悬疑">悬疑</Select.Option>
                  <Select.Option value="武侠">武侠</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Select.Option value="draft">草稿</Select.Option>
                  <Select.Option value="published">已发布</Select.Option>
                  <Select.Option value="archived">已归档</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="description"
                label="简介"
                rules={[{ required: true, message: '请输入小说简介' }]}
              >
                <Input.TextArea rows={4} placeholder="请输入小说简介" />
              </Form.Item >

              <Form.Item
                name="coverImage"
                label="封面图片URL"
              >
                <Input placeholder="请输入封面图片URL" />
              </Form.Item>
            </Form >
          </Modal >

          {/* Import Chapter Modal */}
          <Modal
            title="导入章节"
            open={importModalVisible}
            onCancel={() => setImportModalVisible(false)}
            footer={[
              <Button key="cancel" onClick={() => setImportModalVisible(false)}>取消</Button>,
              <Button key="import" type="primary" loading={importLoading} onClick={handleImportChapter}>导入</Button>
            ]}
          >
            <Input
              placeholder="请输入文件地址"
              value={filePath}
              onChange={(e) => setFilePath(e.target.value)}
              style={{ marginBottom: 16 }}
            />
          </Modal>

          {/* Add/Edit Chapter Modal */}
          < Modal
            title={chapterModalType === 'add' ? "添加章节" : "编辑章节"}
            open={chapterModalVisible}
            onCancel={() => setChapterModalVisible(false)}
            footer={[
              <Button key="cancel" onClick={() => setChapterModalVisible(false)}>
                取消
              </Button>,
              <Button key="submit" type="primary" loading={chapterLoading} onClick={handleChapterSubmit}>
                {chapterModalType === 'add' ? '添加' : '更新'}
              </Button>,
            ]}
            width={800}
          >
            <Form
              form={chapterForm}
              layout="vertical"
              name="chapter_form"
            >
              <Form.Item name="id" hidden>
                <Input />
              </Form.Item>
              <Form.Item
                name="title"
                label="章节标题"
                rules={[{ required: true, message: '请输入章节标题' }]}
              >
                <Input placeholder="请输入章节标题" />
              </Form.Item>

              <Form.Item
                name="sort"
                label="排序"
                rules={[{ required: true, message: '请输入排序号' }]}
              >
                <InputNumber min={1} placeholder="请输入排序号" />
              </Form.Item>

              <Form.Item
                name="content"
                label="章节内容"
                rules={[{ required: true, message: '请输入章节内容' }]}
              >
                <Input.TextArea rows={10} placeholder="请输入章节内容" />
              </Form.Item>
            </Form >
          </Modal >
        </Card>
      </Space>
    </div>
  );
};

export default NovelStore;